package com.xcms.test.news;

import Homework.cms.util.Page;
import Homework.cms.util.ResultFs;
import Homework.cms.util.JDBCHelper;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    public static boolean insert(News news){
        String sql="INSERT INTO news(title,addtime,url) VALUES (?,?,?)";
        Timestamp nowtime = new Timestamp((new java.util.Date()).getTime());
        int cout= JDBCHelper.update(sql,news.getTitle(),nowtime,news.getUrl());
        return cout>0;
    }

    public static boolean remove(News news){
        String sql="DELETE FROM news WHERE id="+news.getId();
        int cout= JDBCHelper.delete(sql);
        return cout>0;
    }

    public static Page<News> getPage(int pageSize, int currPage){
        Page<News> page=null;
        int totalCount=0;
        String sql="SELECT count(1) from news"; //得到数据库中有多少条数据，count(1)比count(*)运行快
        try {
            //1.获取总条数
            ResultSet rs=JDBCHelper.query(sql);
            if(rs.next())   //如果能查到数据
            {
                totalCount=rs.getInt(1);    //得到第一列的数据（数据总条数）
            }
            page=new Page<News>(totalCount,pageSize,currPage);
            //2.设置当前页的数据
            sql="SELECT * FROM news ORDER BY id DESC LIMIT "+page.getCurrpageindex()+","+pageSize;  //当前页的索引和每一页的大小
            rs=JDBCHelper.query(sql);
            List<News> news= ResultFs.getList(rs,"com.xcms.test.news.News");
            page.setRecords(news);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally {
            JDBCHelper.close();
        }
        return page;
    }

    public static List<News> getLatestNews() {
        List<News> news=new ArrayList<>();
        try {
            ResultSet rs= JDBCHelper.query("SELECT * FROM news ORDER BY id DESC LIMIT 0,10");
 //         while (rs!=null&&rs.next())
//            {
//                News n=new News();
//                n.setTitle(rs.getString("title"));
//                n.setUrl(rs.getString("url"));
//                news.add(n);
//            }
            news= ResultFs.getList(rs,"com.xcms.test.news.News");
        } catch (Exception e) {
            System.out.println("获取新闻数据出错"+e.getMessage());
        } finally {
            JDBCHelper.close();
        }

        return news;
    }
}
